import time
import threading
from badbot import Badbot


# how many seconds to wait before we check for more games in HQ
WAIT_CHECK_GAMES = 10
AI_BADBOT_NAME = "ai_PuzzleBot"
AI_BADBOT_APIKEY = "ZR9GuocRZYmoUKTtuKf2UZTYT"

class GameRunThread(threading.Thread):
  ''' Intended to run games in separate threads so we can do more than 1 at once. '''
  def run(self):
    try:
      if not self.gameid:
        print "No gameid"
        return
      elif not self.bot:
        print "No bot!"
        return
      else:
        self.bot.playTurn(self.gameid)
        print "--- End turn for %d ---" % self.gameid
    finally:
        self.playinglist.remove(self.gameid)

if __name__ == "__main__":
  bot = Badbot(AI_BADBOT_NAME, AI_BADBOT_APIKEY)
  playinglist = []
  while True:
    try:
      bot.getInfo()
      for mygame in bot.info.game:
        gameid = int(mygame.id.PCDATA)
        if mygame.__dict__.has_key("inNeedOfAttention") and mygame.inNeedOfAttention == u"true":
          if gameid not in playinglist:
            print "Scheduling turn: %d" %gameid
            playinglist.insert(0,gameid)
            newthread = GameRunThread()
            newthread.gameid = gameid
            newthread.bot = Badbot(AI_BADBOT_NAME, AI_BADBOT_APIKEY)
            newthread.playinglist = playinglist
            newthread.start()
      time.sleep(WAIT_CHECK_GAMES)
    except Exception, e:
      print "ERROR:", e
      time.sleep(30)
